<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="800"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div>
      <yt-crud
        v-bind="options"
        ref="crudRef"
        @onLoad="getData"
        :fun-props="{
          exportBtn: false,
          delBtn: false,
        }"
        :table-props="{
          selection: false,
          delBtn: true,
          pageHide: true,
          viewBtn: false,
          editBtn: false,
          menuSlot: true,
        }"
        :form-props="{
          loading: state.form.loading,
          width: 500,
        }"
        :loading="state.loading"
        :total="state.total"
        v-model:page="state.page"
        v-model:query="state.query"
        @delFun="handleDelete"
        @saveFun="onSave"
        @openBeforeFun="openBeforeFun"
        @change="onChange"
      >
        <template #rightToolbar></template>
        <template #status="scope:any">
          <DictTag :options="EnableStatusEnum" :value="scope.row.status" />
        </template>
        <template #menuSlot="scope:any">
          <div class="menu-btn">
            <el-tooltip class="box-item" effect="dark" :content="t('system.agentStation.action.bindDealer')" placement="top">
              <el-button link type="primary" icon="grid" @click="handlerStationDealerList(scope.row)" />
            </el-tooltip>
            <el-divider direction="vertical" />
          </div>
        </template>
      </yt-crud>
    </div>

    <template #footer>
      <el-button @click="handleClose" :loading="state.loading">{{t('crud.closeText')}}</el-button>
    </template>

    <StationDealerList ref="stationDealerRef" @success="handleSuccess" />
  </el-dialog>
</template>

<script lang="ts" setup>

import YtCrud from '@/components/common/yt-crud.vue'
import {IColumn} from '@/components/common/types/tableCommon'
import {agentStationList, agentStationDelete, agentStationBatchDelete, agentStationSave} from '@/api/system/agentStation'
import {optionSelect as stationOptionSelect} from '@/api/business/station'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'

import StationDealerList from '@/views/system/agent/modules/stationDealerList.vue'

const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum'))

const emits = defineEmits(['success'])

const stationDealerRef = ref()

const state = reactive({
  visible: false,
  loading: false,
  recharge: {},
  form: {
    loading: false,
  },
  title: t('system.agent.action.bindStation'),
  page: {
    pageSize: 30,
    pageNum: 1,
  },
  total: 0,
  query: {},
})

const agent = ref<any>({})
const stations = ref<any[]>([])

const column = ref<IColumn[]>([
  {
    label: t('system.agentStation.stationId'),
    key: 'stationId',
    type: 'i18nSelect',
    search: false,
    formHide: false,
    slot: false,
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      options: stations,
    },
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    componentProps: {
      type: 'textarea',
      rows: 5,
    }
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])

const openDialog = (row?: any) => {
  agent.value = row
  state.visible = true
}

const handleClose = () => {
  state.visible = false
}

const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})

const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  agentStationList({
    ...state.page,
    ...state.query,
    ...{ agentId: agent.value.id}
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

const getDict = () => {
  stationOptionSelect({}).then((res) => {
    res.data.forEach((item)=>{
      item.disabled = !!item.agentId
    })
    stations.value = res.data
  })
}

getDict()

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  agentStationSave(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
    getDict()

    emits('success')
  }).finally(()=>{
    state.loading = false
  })
}


// 弹窗前置操作
const openBeforeFun = ({ type, data }) => {
  if (type === 'add') {
    data.agentId = agent.value.id
  } else if (type === 'update') { /* empty */ }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    await agentStationBatchDelete(row.map((m) => m.id))
  } else {
    await agentStationDelete(row.id)
  }
  ElMessage.success(t('operate.tooltip.success'))
  state.loading = false
  getData()
  getDict()
}

const handlerStationDealerList = (row: any) => {
  stationDealerRef.value.openDialog(row)
}

const handleSuccess = () => {}

const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>
